package domotica.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeSelectionModel;

import domotica.houseowner.HouseOwner;

public class DomoticaGUI extends JFrame implements TreeSelectionListener{
	
	private JTree tree;
	private JPanel domoPanel;
	private JPanel actuatorSensorPane;
	private HouseOwner houseOwner;
	private JSplitPane splitPane;
	private JScrollPane actuatorSensorView;
	private Map<String, SlidersJPanel> jPanelCache;
	
	public DomoticaGUI(HouseOwner houseOwner, int width, int height) {
		
		this.houseOwner = houseOwner;
		
		this.setIconImage(DomoticaGUI.createImage("images/logoframe1.gif"));
		this.setSize(width, height);		
		this.setLocationByPlatform(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle("Domotica");
		
		this.jPanelCache = new HashMap<String, SlidersJPanel>();
		
	
        domoPanel = new JPanel(new GridLayout(1,0));    
        domoPanel.setOpaque(true);
        
        DefaultMutableTreeNode top =
            new DefaultMutableTreeNode("ActuatorsSensors");
        
        createNodes(top);

        //Create a tree that allows one selection at a time.
        tree = new JTree(top);
        tree.getSelectionModel().setSelectionMode
                (TreeSelectionModel.SINGLE_TREE_SELECTION);
        
      //Set the icon for leaf nodes.
        ImageIcon leafIcon = createImageIcon("images/gears.gif");
        if (leafIcon != null) {
            DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
            renderer.setLeafIcon(leafIcon);
            tree.setCellRenderer(renderer);
        } else {
            System.err.println("Leaf icon missing; using default.");
        }
        
        //Listen for when the selection changes.
        tree.addTreeSelectionListener(this);
        
        //Create the scroll pane and add the tree to it. 
        JScrollPane treeView = new JScrollPane(tree);
               
        actuatorSensorPane = new JPanel();
//      actuatorSensorView = new JScrollPane(actuatorSensorPane);
        
        splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setTopComponent(treeView);
        splitPane.setBottomComponent(actuatorSensorPane);
        
        Dimension minimumSize = new Dimension(100, 200);
        actuatorSensorPane.setMinimumSize(minimumSize);
        treeView.setMinimumSize(minimumSize);
        splitPane.setDividerLocation(175); 
    
        domoPanel.add(splitPane);
        
		this.add(domoPanel,BorderLayout.CENTER);
        
	}

	private void createNodes(DefaultMutableTreeNode top) {
	
		for(String name: this.houseOwner.getActuatorsSensorsNameList()){
			top.add(new DefaultMutableTreeNode(name));
		}
		
	}

	public void valueChanged(TreeSelectionEvent e) {
		
		DefaultMutableTreeNode node = (DefaultMutableTreeNode)
        tree.getLastSelectedPathComponent();

		if (node == null) 
			return;
		JPanel jpanel;
		Object nodeInfo = node.getUserObject();
		if (node.isLeaf()){
			if(this.jPanelCache.containsKey((String) nodeInfo)){ 
				jpanel = ActuatorSensorGUI.getActuatorSensorGUI(this.jPanelCache.get((String) nodeInfo), ((String) nodeInfo));
			}else{
				jpanel = ActuatorSensorGUI.getActuatorSensorGUI(this, this.houseOwner, (String)nodeInfo);
			}
			splitPane.setBottomComponent(jpanel);
		}
		
	}
	
	protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = DomoticaGUI.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
	
	protected static Image createImage(String path){
		
		BufferedImage image = null;
        try {
            image = ImageIO.read(DomoticaGUI.class.getResource(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
		return image;

	}

	public void addActuatorSensorCacheElement(String actuatorSensorName,
			SlidersJPanel panel2) {
		this.jPanelCache.put(actuatorSensorName, panel2);
		
	}
	
//	private static void createAndShowGUI() {
//        //Create and set up the window.
//        JFrame frame = new JFrame("Domotica Web Service");
//        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//
//        //Create and set up the content pane.
////        DomoticaGUI newContentPane = new DomoticaGUI();
////        newContentPane.setOpaque(true); //content panes must be opaque
////        frame.setContentPane(newContentPane);
//
//        //Display the window.
//        frame.pack();
//        frame.setVisible(true);
//    }
	
//	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
//		
//        //Schedule a job for the event-dispatching thread:
//        //creating and showing this application's GUI.
//        javax.swing.SwingUtilities.invokeLater(new Runnable() {
//            public void run() {
//         //       createAndShowGUI();
//            	try
//        		{
//        			DomoticaGUI gui=new DomoticaGUI(null, 270, 300);
//        			gui.setVisible(true);
//        		}
//        		catch(Exception e)
//        		{JOptionPane.showMessageDialog(null, e.getMessage());}
//            }
//        });
//    }

}
